<template>
  <div class="msg_main">
    <div class="msg_box" v-if="user">
        <div class="header">与 {{user.nickname}} 的聊天</div>
        <div class="msg_list" @drop.prevent="dropImage" @dragover.prevent="dropImageOver">
          <vue-scroll v-viewer  @handle-scroll="msglistscroll" @handle-resize="handleResize" ref="msg_list" :ops="msg_list.ops" class="msg_list_box">
            <center><a><font color="#2c90ff" @click="getChatLog">查看更多消息</font></a></center>
            <msg-item v-for="(item, index) in user.chatlog" :key="index" :data="item" :user="user" :csuser="csuser"></msg-item>
          </vue-scroll>
        </div>
        <div class="input">
          <div class="toolebar">
            <div class="tools face" v-clickout @clickout="face.show = false" :class="{active:face.show}">
              <Icon type="md-happy" @click="face.show = !face.show" />
              <div class="facebox" v-if="face.show">
                <vue-scroll :ops="face.ops">
                  <span v-for="(item, index) in face.list" :key="index" @click="addFace(item)">{{item}}</span>
                </vue-scroll>
              </div>
            </div>
            <div class="tools upimg" @click="uploadImages"><Icon type="md-images" /></div>
            <div class="tools printuser" @click="printuser"><Icon type="ios-paper-plane" />打印用户</div>
          </div>
          <div class="text">
            <textarea @keydown="textKeyDown" ref="msg_input" v-model="user.msg_input"></textarea>
            <div class="btn">
              按下 Shift + Enter 键换行
              <button class="send" @click="sendMsg">发送</button>
            </div>
          </div>
        </div>
    </div>
    <div class="no_msg" v-else>
        <p>
          <Icon type="md-bug" />当前没有聊天
        </p>
    </div>
  </div>
</template>

<script>
import face from '../../assets/js/face.js'
import msgItem from '../msg-item/msg-item'

export default {
  name: 'test',
  data: () => {
    return {
      msg_list: {
        ops: {
          vuescroll: {
            mode: 'native'
          },
          scrollPanel: {
            initialScrollY: '100%',
            speed: 10
          },
          rail: {
            size: '3px',
            gutterOfSide: '0px'
          },
          bar: {
            background: '#3e58c9',
            opacity: 0.6
          }
        }
      },
      face: {
        show: false,
        list: face,
        ops: {
          vuescroll: {
            mode: 'native'
          },
          scrollPanel: {},
          rail: {
            size: '3px',
            gutterOfSide: '0px'
          },
          bar: {
            background: '#3e58c9',
            opacity: 0.6
          }
        }
      }
    }
  },
  props: {
    user: {
      default: null
    },
    csuser: {
      default: null
    },
    sendMsgs: {
      default: null
    }
  },
  components: {
    'msg-item': msgItem
  },
  watch: {
    user: function (newVal, oldVal) {
      if (newVal && oldVal) {
        if (newVal.user_id !== oldVal.user_id) {
          this.$refs['msg_list'].refresh()
          this.$refs['msg_list'].scrollTo({
            y: '100%'
          })
        }
      }
    }
  },
  created () {
  },
  mounted () {
  },
  methods: {
    printuser () {
      console.log(this.user)
    },
    handleResize () {
      if (this.user.receiveMsg) { // 新消息 滚动到底部
        this.user.receiveMsg = false
        this.$refs['msg_list'].refresh()
        this.$refs['msg_list'].scrollTo({
          y: '100%'
        })
      }
    },
    msglistscroll (vertical) {
    },
    getChatLog () {
      var that = this
      var oldH = this.$refs['msg_list'].$refs.scrollContent.offsetHeight
      this.$http.post(this.$store.state.sever_url + '/User/getChatLog', {
        cs_id: this.csuser.id,
        openid: this.user.openid,
        last_time: this.user.chatlog[0].send_time
      }).then(function (response) {
        if (response.data.status === 1) {
          response.data.chatlog.reverse()
          response.data.chatlog.push(...that.user.chatlog)
          that.user.chatlog = response.data.chatlog
          setTimeout(function () {
            var newH = that.$refs['msg_list'].$refs.scrollContent.offsetHeight
            console.log(newH)
            if (newH === oldH) {
              that.$Message.warning('没有新消息了')
            } else {
              that.$refs['msg_list'].refresh()
              that.$refs['msg_list'].scrollTo({
                y: newH - oldH
              })
            }
          }, 0)
        } else {
          that.$Message.warning('没有新消息了')
        }
      }).catch(function (err) {
        console.log(err)
        that.$Message.warning('没有新消息了')
      })
    },
    open (link) {
      this.$electron.shell.openExternal(link)
    },
    addFace (face) {
      this.user.msg_input = this.user.msg_input || ''
      this.user.msg_input += face
      this.$refs.msg_input.innerHTML = this.user.msg_input
      this.$forceUpdate()
    },
    dropImageOver () {
      console.log(1)
    },
    dropImage (e) {
      this.sendPicmsg(e.dataTransfer.files[0])
    },
    textKeyDown (e) {
      if (e.keyCode === 13 && !e.shiftKey) {
        e.preventDefault()
        this.sendMsg()
      }
    },
    uploadImages () {
      var that = this
      this.$fn.uploadMsgimg().then(function (file) {
        that.sendPicmsg(file)
      }).catch(function (err) {
        console.error(err)
      })
    },
    sendPicmsg (file) {
      var msg = {
        appid: this.csuser.appid,
        openid: this.user.openid,
        cs_id: this.csuser.id,
        type: 'image',
        image: file,
        content: this.$fn.getObjectURL(file),
        send_type: 1002,
        send_time: Date.parse(new Date()) / 1000,
        send_state: 2
      }
      this.user.chatlog.push(msg)
      this.$forceUpdate()
      this.$refs['msg_list'].scrollTo({
        y: '200%'
      })
      this.sendMsgs(msg, this.user, this.user.chatlog.length - 1)
    },
    sendMsg () {
      var str = this.user.msg_input || ''
      str = str.replace(/^(\s|\u00A0)+/, '').replace(/(\s|\u00A0)+$/, '')
      if (str === '') {
        this.$Message.warning('不能发送空白消息')
        return
      }
      var msg = {
        appid: this.csuser.appid,
        openid: this.user.openid,
        cs_id: this.csuser.id,
        type: 'text',
        content: this.user.msg_input,
        send_type: 1002,
        send_time: Date.parse(new Date()) / 1000,
        send_state: 2
      }
      this.user.chatlog.push(msg)
      this.user.msg_input = ''
      this.$forceUpdate()
      this.$refs['msg_list'].scrollTo({
        y: '200%'
      })
      this.sendMsgs(msg, this.user, this.user.chatlog.length - 1)
    }
  }
}
</script>

<style lang="less" scoped>
@import './style.less';
</style>
